#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx
import wx.grid
import os,string
import pymssql
import MainGrid
import AddDialog,EditDialog,ViewDialog,AboutDialog
import threading

#获取查询运行目录，使用ICON资料夹图标
mypath=os.getcwd()
addpic=string.replace(mypath+'\\icons\\add.png','\\','/')
edtpic=string.replace(mypath+'\\icons\\edit.png','\\','/')
delpic=string.replace(mypath+'\\icons\\del.png','\\','/')
detpic=string.replace(mypath+'\\icons\\detail.png','\\','/')
extpic=string.replace(mypath+'\\icons\\exit.png','\\','/')
refpic=string.replace(mypath+'\\icons\\refresh.png','\\','/')

#共用的数据库连接函数
def DBConnection():
    conn=pymssql.connect(host='127.0.0.1',user='sa',password='',database='testdb2',charset='gbk' )
    cur=conn.cursor()
    return conn,cur
        
class MainFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        self.SqlHistory=""
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.static_line_1 = wx.StaticLine(self, -1)
        self.grid_1 = wx.grid.Grid(self, -1,size=(1, 1))
        
        #调用私有方法设置窗口部件属性和位置
        self.__set_properties()
        self.__do_layout()
        
        #初始化时绑定各种事件
        self.Bind(wx.EVT_TOOL,self._OnAddDialog,None,2001)
        self.Bind(wx.EVT_BUTTON,self._ToolButton,None,2009)
        self.Bind(wx.EVT_TOOL,self._OnClose,None,2006)
        self.Bind(wx.EVT_TOOL,self._DelRow,None,2004)
        self.Bind(wx.EVT_TOOL,self._Refresh,None,2005)
        self.Bind(wx.EVT_TOOL,self._EditRow,None,2002)
        self.Bind(wx.EVT_TOOL,self._ViewRow,None,2003)
        self.grid_1.Bind(wx.grid.EVT_GRID_RANGE_SELECT,self._StatusBar_ShowSelect)
        self.grid_1.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK,self.OnLabelRightClicked)
        self.Bind(wx.EVT_MENU,self._about,None,1031)
        self.Bind(wx.EVT_MENU,self._OnClose,None,1012)
        self.Bind(wx.EVT_MENU,self._OnAddDialog,None,1021)
        self.Bind(wx.EVT_MENU,self._EditRow,None,1022)
        self.Bind(wx.EVT_MENU,self._ViewRow,None,1023)
        self.Bind(wx.EVT_MENU,self._DelRow,None,1024)
        self.Bind(wx.EVT_TEXT_ENTER,self._ToolButton,None,2008)

    def __set_properties(self):
        self.SetTitle("MainForm")
        self.SetSize((800, 600))
        
    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(self.static_line_1, 0, wx.EXPAND, 0)
        sizer_1.Add(self.grid_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        
        #添加菜单栏 工具栏和状态栏----------------
        self.menubar=MainMenuBar()
        self.toolbar=MainToolBar(self)
        self.statusbar=MainStatusbar(self)
        self.SetMenuBar(self.menubar)
        self.SetToolBar(self.toolbar)
        self.SetStatusBar(self.statusbar)
        self.Layout()
        #-----------------------------------------
        
     
    #添加修改同步刷新显示------------------   
    def SyncRefres(self):
        if self.SqlHistory=="":
            pass
        else:
            try:
                conn,cur=DBConnection()
                cur.execute(self.SqlHistory)
                self._SetGrid(cur) 
                cur.close()
                conn.close()
            except:
                wx.MessageBox(u"数据库连接错误！刷新失败。",u"错误")
                
    def _Refresh(self,evt):
        self.SyncRefres()
        
    #一个用数据库时间格式设置Wx时间格式的方法--------------
    def PY2DMY(self,TimeString):
        pyDate=(TimeString.split()[0])
        pyTime=(TimeString.split()[1])
                
        DMYYear=int(pyDate.split("-")[0])
        DMYMonth=int(pyDate.split("-")[1])-1 #月从0开始，所以-1
        DMYDay=int(pyDate.split("-")[2])
                
        DMYdate=wx.DateTimeFromDMY(DMYDay,DMYMonth,DMYYear)
        return DMYdate,pyTime
    #---------------------------------------------------------
    
    def _EditRow(self,evt):
        #取得选取行的行数
        rows = self.grid_1.GetSelectedRows()
        if len(rows)==1:
            
            #取得选择行单行的Rkey的值----------
            Rkey=int(self.grid_1.GetRowLabelValue(rows[0]))
            
            #取选择行的各列的值赋给变量--------------------------------
            row=rows[0]
            khdm=self.grid_1.GetCellValue(row,0).strip() #吃掉空格
            khmc=self.grid_1.GetCellValue(row,1).strip()
            yewy=self.grid_1.GetCellValue(row,2).strip()
            bjrq=self.grid_1.GetCellValue(row,3)
            bjyx=self.grid_1.GetCellValue(row,4)
            ddsl=self.grid_1.GetCellValue(row,5)
            ddjs=self.grid_1.GetCellValue(row,6)
            ddff=self.grid_1.GetCellValue(row,7)
            hth=self.grid_1.GetCellValue(row,8)
            ycsl=self.grid_1.GetCellValue(row,9)
            ycyy=self.grid_1.GetCellValue(row,10)
            czsj=self.grid_1.GetCellValue(row,11)
            xgsj=self.grid_1.GetCellValue(row,12)
            hcsj=self.grid_1.GetCellValue(row,13)
            xgyy=self.grid_1.GetCellValue(row,14)
            half=self.grid_1.GetCellValue(row,15)
            two=self.grid_1.GetCellValue(row,16)
            day=self.grid_1.GetCellValue(row,17)
            tcry=self.grid_1.GetCellValue(row,18)
            tcff=self.grid_1.GetCellValue(row,19)
            noback=self.grid_1.GetCellValue(row,20)
            zzzq=self.grid_1.GetCellValue(row,21)
            tczq=self.grid_1.GetCellValue(row,22)
            bz=self.grid_1.GetCellValue(row,23)
            #--------------------------------------------------------
            
            #初始化一个值，用来形成EditDialog的是否自动判断的条件(失去焦点事件)
            dlg=EditDialog.EditDialog(self,-1,"",khdm)
            
            #开始为打开的EditDialog设置值------------------------------------
            dlg.khdm_ctrl.SetValue(khdm)
            dlg.khmc_ctrl.SetValue(khmc)
            dlg.yewy_ctrl.SetValue(yewy)
            bjrq_date,bjrq_time=self.PY2DMY(bjrq)
            dlg.bjrq_datectrl.SetValue(bjrq_date)
            bjyx_date,bjyx_time=self.PY2DMY(bjyx)
            dlg.bjyx_datectrl.SetValue(bjyx_date)
            dlg.ddsl_ctrl.SetValue(ddsl)
            ddjs_date,ddjs_time=self.PY2DMY(ddjs)
            dlg.ddjs_datectrl.SetValue(ddjs_date)
            dlg.ddjs_timectrl.SetValue(ddjs_time)
            ddff_date,ddff_time=self.PY2DMY(ddff)
            dlg.ddff_datectrl.SetValue(ddff_date)
            dlg.ddff_timectrl.SetValue(ddff_time)
            dlg.hth_ctrl.SetValue(hth.strip())
            dlg.ycsl_ctrl.SetValue(ycsl)
            dlg.ycyy_ctrl.SetValue(ycyy)
            czsj_date,czsj_time=self.PY2DMY(czsj)
            dlg.czsj_datectrl.SetValue(czsj_date)
            dlg.czsj_timectrl.SetValue(czsj_time)
            xgsj_date,xgsj_time=self.PY2DMY(xgsj)
            dlg.xgsj_datectrl.SetValue(xgsj_date)
            dlg.xgsj_timectrl.SetValue(xgsj_time)
            hcsj_date,hcsj_time=self.PY2DMY(hcsj)
            dlg.hcsj_datectrl.SetValue(hcsj_date)
            dlg.hcsj_timectrl.SetValue(hcsj_time)
            dlg.xgyy_ctrl.SetValue(xgyy)
            dlg.half_ctrl.SetValue(half)
            dlg.two_ctrl.SetValue(two)
            dlg.day_ctrl.SetValue(day)
            dlg.tcry_ctrl.SetValue(tcry)
            tcff_day,tcff_time=self.PY2DMY(tcff)
            dlg.tcff_datectrl.SetValue(tcff_day)
            dlg.tcff_timectrl.SetValue(tcff_time)
            dlg.noback_ctrl.SetValue(noback)
            dlg.zzzq_ctrl.SetValue(zzzq)
            dlg.tczq_ctrl.SetValue(tczq)
            dlg.bz_ctrl.SetValue(bz)
            #--------------------------------------------------
            dlg.CenterOnScreen()
            retVal = dlg.ShowModal()
            if retVal==wx.ID_OK:
                #------------------------------------------------
                khdm=self.GetTextValue(dlg.khdm_ctrl)
                khmc=self.GetTextValue(dlg.khmc_ctrl)
                yewy=self.GetTextValue(dlg.yewy_ctrl)
                bjrq=dlg._wxdate2pydate(dlg.bjrq_datectrl.GetValue())
                bjyx=dlg._wxdate2pydate(dlg.bjyx_datectrl.GetValue())
                ddsl=int(self.GetTextValue(dlg.ddsl_ctrl))
                ddjs=dlg.HBTime(dlg.ddjs_datectrl.GetValue(),dlg.ddjs_timectrl.GetValue())
                ddff=dlg.HBTime(dlg.ddff_datectrl.GetValue(),dlg.ddff_timectrl.GetValue())
                hth=self.GetTextValue(dlg.hth_ctrl)
                ycsl=int(self.GetTextValue(dlg.ycsl_ctrl))
                ycyy=self.GetTextValue(dlg.ycyy_ctrl)
                czsj=dlg.HBTime(dlg.czsj_datectrl.GetValue(),dlg.czsj_timectrl.GetValue())
                xgsj=dlg.HBTime(dlg.xgsj_datectrl.GetValue(),dlg.xgsj_timectrl.GetValue())
                hcsj=dlg.HBTime(dlg.hcsj_datectrl.GetValue(),dlg.hcsj_timectrl.GetValue())
                xgyy=self.GetTextValue(dlg.xgyy_ctrl)
                half=self.GetTextValue(dlg.half_ctrl)
                two=self.GetTextValue(dlg.two_ctrl)
                day=self.GetTextValue(dlg.day_ctrl)
                tcry=self.GetTextValue(dlg.tcry_ctrl)
                tcff=dlg.HBTime(dlg.tcff_datectrl.GetValue(),dlg.tcff_timectrl.GetValue())
                noback=self.GetTextValue(dlg.noback_ctrl)
                zzzq=self.GetTextValue(dlg.zzzq_ctrl)
                tczq=self.GetTextValue(dlg.tczq_ctrl)
                bz=self.GetTextValue(dlg.bz_ctrl)

                self._UpdateSQL(khdm,khmc,yewy,bjrq,bjyx,ddsl,ddjs,ddff,hth,ycsl,ycyy,czsj,
                           xgsj,hcsj,xgyy,half,two,day,tcry,tcff,noback,zzzq,tczq,bz,Rkey)
                
                self.SyncRefres() #同步刷新显示
            else:
                pass
            
            dlg.Destroy()   
                #---------------------
        elif len(rows)>1:
            wx.MessageBox(u"无法编辑多行",u"错误")
        else:
            pass #当选择列时不处理-1
            
        
    def _ViewRow(self,evt):
        rows = self.grid_1.GetSelectedRows()
        if len(rows)==1:
            Rkey=int(self.grid_1.GetRowLabelValue(rows[0])) #同EditRow
            row=rows[0]
            khdm=self.grid_1.GetCellValue(row,0).strip()
            khmc=self.grid_1.GetCellValue(row,1).strip()
            yewy=self.grid_1.GetCellValue(row,2).strip()
            bjrq=self.grid_1.GetCellValue(row,3)
            bjyx=self.grid_1.GetCellValue(row,4)
            ddsl=self.grid_1.GetCellValue(row,5)
            ddjs=self.grid_1.GetCellValue(row,6)
            ddff=self.grid_1.GetCellValue(row,7)
            hth=self.grid_1.GetCellValue(row,8)
            ycsl=self.grid_1.GetCellValue(row,9)
            ycyy=self.grid_1.GetCellValue(row,10)
            czsj=self.grid_1.GetCellValue(row,11)
            xgsj=self.grid_1.GetCellValue(row,12)
            hcsj=self.grid_1.GetCellValue(row,13)
            xgyy=self.grid_1.GetCellValue(row,14)
            half=self.grid_1.GetCellValue(row,15)
            two=self.grid_1.GetCellValue(row,16)
            day=self.grid_1.GetCellValue(row,17)
            tcry=self.grid_1.GetCellValue(row,18)
            tcff=self.grid_1.GetCellValue(row,19)
            noback=self.grid_1.GetCellValue(row,20)
            zzzq=self.grid_1.GetCellValue(row,21)
            tczq=self.grid_1.GetCellValue(row,22)
            bz=self.grid_1.GetCellValue(row,23)
            
            #产生ViewDialog对话窗体
            dlg=ViewDialog.ViewDialog(self)

            dlg.khdm_ctrl.SetValue(khdm)
            dlg.khmc_ctrl.SetValue(khmc)
            dlg.yewy_ctrl.SetValue(yewy)
            bjrq_date,bjrq_time=self.PY2DMY(bjrq)
            dlg.bjrq_datectrl.SetValue(bjrq_date)
            bjyx_date,bjyx_time=self.PY2DMY(bjyx)
            dlg.bjyx_datectrl.SetValue(bjyx_date)
            dlg.ddsl_ctrl.SetValue(ddsl)
            ddjs_date,ddjs_time=self.PY2DMY(ddjs)
            dlg.ddjs_datectrl.SetValue(ddjs_date)
            dlg.ddjs_timectrl.SetValue(ddjs_time)
            ddff_date,ddff_time=self.PY2DMY(ddff)
            dlg.ddff_datectrl.SetValue(ddff_date)
            dlg.ddff_timectrl.SetValue(ddff_time)
            dlg.hth_ctrl.SetValue(hth.strip())
            dlg.ycsl_ctrl.SetValue(ycsl)
            dlg.ycyy_ctrl.SetValue(ycyy)
            czsj_date,czsj_time=self.PY2DMY(czsj)
            dlg.czsj_datectrl.SetValue(czsj_date)
            dlg.czsj_timectrl.SetValue(czsj_time)
            xgsj_date,xgsj_time=self.PY2DMY(xgsj)
            dlg.xgsj_datectrl.SetValue(xgsj_date)
            dlg.xgsj_timectrl.SetValue(xgsj_time)
            hcsj_date,hcsj_time=self.PY2DMY(hcsj)
            dlg.hcsj_datectrl.SetValue(hcsj_date)
            dlg.hcsj_timectrl.SetValue(hcsj_time)
            dlg.xgyy_ctrl.SetValue(xgyy)
            dlg.half_ctrl.SetValue(half)
            dlg.two_ctrl.SetValue(two)
            dlg.day_ctrl.SetValue(day)
            dlg.tcry_ctrl.SetValue(tcry)
            tcff_day,tcff_time=self.PY2DMY(tcff)
            dlg.tcff_datectrl.SetValue(tcff_day)
            dlg.tcff_timectrl.SetValue(tcff_time)
            dlg.noback_ctrl.SetValue(noback)
            dlg.zzzq_ctrl.SetValue(zzzq)
            dlg.tczq_ctrl.SetValue(tczq)
            dlg.bz_ctrl.SetValue(bz)
            
            dlg.CenterOnScreen()
            retVal = dlg.ShowModal()
            if retVal==wx.ID_CANCEL:
                pass
            
            dlg.Destroy()
            
        elif len(rows)>1:
            wx.MessageBox(u"无法查看多行！",u"错误")
        else:
            pass #当选择列时不处理
                 
    def _DelRow(self,evt):
        rows=self.grid_1.GetSelectedRows() #形成一个选择行的列表
        RowLabels=[] # 初始化一个空的列表用来存储选择行的标签
        succeed_del_rows=[] #初始化一个空的列表用来存储已成功从数据库删除的行
        num=0
        
        for row in rows:
            RowLabel=self.grid_1.GetRowLabelValue(row).encode("gbk")
            RowLabels.append(RowLabel)   
        # 遍历整个选择后提示是否删除
        
        if len(rows)!=0:
            dlg=wx.MessageDialog(None,u"是否删除标记为%s的记录!"%RowLabels,u"警告",wx.YES_NO|wx.ICON_WARNING)
        
            retval=dlg.ShowModal()
        
            if retval==wx.ID_YES:
            #实例化一个进度条用来显示删除进度
                DelGauge=wx.Gauge(self,-1,(len(RowLabels)),size=(250,25))
                DelGauge.CentreOnParent()
                DelGauge.SetBezelFace(3)
                DelGauge.SetShadowWidth(3)
            
                for row in rows:
                    num=num+1
                    Rkey=int(self.grid_1.GetRowLabelValue(row).encode("gbk"))
                    try:
                        self._DelSQL(Rkey)  #从数据库中删除选择的记录
                        #print Rkey
                        succeed_del_rows.append(row) #如成功删除，则把此行加入待更新列表
                        DelGauge.SetValue(num)
                    except:
                        wx.MessageBox(u"数据库连接错误！无法删除 %s 。"%(Rkey),u"错误")
                    
                DelGauge.Hide()
                
                try:
                    self._table.DeleteRows(succeed_del_rows)
                    self.Reset()
                except AttributeError:
                    wx.MessageBox(u"请查询后选择要删除的行",u"错误")
            else:
                pass
        else:
            pass
        
    def Reset(self):
        self._table.ResetView(self.grid_1)  #MainGrid的Reset自定义刷新方法
             
    def _OnClose(self,evt):
        dlg=wx.MessageDialog(None,u"是否退出此程序！",u"确认",style=wx.YES_NO|wx.ICON_INFORMATION)
        retval=dlg.ShowModal()
        if retval==wx.ID_YES:
            self.Close()
        else:
            pass

    def _OnAddDialog(self,evt):
        dlg=AddDialog.AddDialog(self)
        dlg.CenterOnScreen()
        retVal = dlg.ShowModal()
        if retVal==wx.ID_OK:
            khdm=self.GetTextValue(dlg.khdm_ctrl)
            khmc=self.GetTextValue(dlg.khmc_ctrl)
            yewy=self.GetTextValue(dlg.yewy_ctrl)
            bjrq=dlg._wxdate2pydate(dlg.bjrq_datectrl.GetValue())
            bjyx=dlg._wxdate2pydate(dlg.bjyx_datectrl.GetValue())
            ddsl=int(self.GetTextValue(dlg.ddsl_ctrl))
            ddjs=dlg.HBTime(dlg.ddjs_datectrl.GetValue(),dlg.ddjs_timectrl.GetValue())
            ddff=dlg.HBTime(dlg.ddff_datectrl.GetValue(),dlg.ddff_timectrl.GetValue())
            hth=self.GetTextValue(dlg.hth_ctrl)
            ycsl=int(self.GetTextValue(dlg.ycsl_ctrl))
            ycyy=self.GetTextValue(dlg.ycyy_ctrl)
            czsj=dlg.HBTime(dlg.czsj_datectrl.GetValue(),dlg.czsj_timectrl.GetValue())
            xgsj=dlg.HBTime(dlg.xgsj_datectrl.GetValue(),dlg.xgsj_timectrl.GetValue())
            hcsj=dlg.HBTime(dlg.hcsj_datectrl.GetValue(),dlg.hcsj_timectrl.GetValue())
            xgyy=self.GetTextValue(dlg.xgyy_ctrl)
            half=self.GetTextValue(dlg.half_ctrl)
            two=self.GetTextValue(dlg.two_ctrl)
            day=self.GetTextValue(dlg.day_ctrl)
            tcry=self.GetTextValue(dlg.tcry_ctrl)
            tcff=dlg.HBTime(dlg.tcff_datectrl.GetValue(),dlg.tcff_timectrl.GetValue())
            noback=self.GetTextValue(dlg.noback_ctrl)
            zzzq=self.GetTextValue(dlg.zzzq_ctrl)
            tczq=self.GetTextValue(dlg.tczq_ctrl)
            bz=self.GetTextValue(dlg.bz_ctrl)
            
            self._InsertSQL(khdm,khmc,yewy,bjrq,bjyx,ddsl,ddjs,ddff,hth,ycsl,ycyy,czsj,
                           xgsj,hcsj,xgyy,half,two,day,tcry,tcff,noback,zzzq,tczq,bz)
    
            self.SyncRefres()
        dlg.Destroy()
        
    def GetTextValue(self,window):
            return window.GetValue().encode("gbk")
    
    
    def _InsertSQL(self,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24):
        try:
            conn,cur=DBConnection()
            cur.execute("INSERT INTO CON_ABN (CUST_CODE,CUST_NAME,SALES_CODE,\
            QUOTE_DATE,QUOTE_LIFE,ORDER_AMOUNT,ORDER_REC_TIME,ORDER_OUT_TIME,\
            CON_NO,ABN_AMOUNT,ABN_CAUSES,CON_FAX_TIME,CON_EDIT_TIME,CON_BACK_TIME,\
            CON_EDIT_CAUSES,HALF_STATUS,TWO_STATUS,DAY_STATUS,PUT_USER,PUT_TIME,\
            NO_BACK_CAUSES,CON_MAKE_CYCLE,CON_PUT_CYCLE,REMARK)\
            VALUES (%s,%s,%s,%s,%s,%d,%s,%s,%s,%d,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24))
            conn.commit() #提交
            cur.close()
            conn.close()
        except:
            wx.MessageBox(u"数据库连接错误！添加记录失败。","Error")
            
    def _UpdateSQL(self,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25):
        try:
            conn,cur=DBConnection()
            cur.execute("update CON_ABN set CUST_CODE=%s,CUST_NAME=%s,SALES_CODE=%s,QUOTE_DATE=%s,\
            QUOTE_LIFE=%s,ORDER_AMOUNT=%d,ORDER_REC_TIME=%s,ORDER_OUT_TIME=%s,CON_NO=%s,ABN_AMOUNT=%d,\
            ABN_CAUSES=%s,CON_FAX_TIME=%s,CON_EDIT_TIME=%s,CON_BACK_TIME=%s,CON_EDIT_CAUSES=%s,\
            HALF_STATUS=%s,TWO_STATUS=%s,DAY_STATUS=%s,PUT_USER=%s,PUT_TIME=%s,NO_BACK_CAUSES=%s,\
            CON_MAKE_CYCLE=%s,CON_PUT_CYCLE=%s,REMARK=%s where RKEY=%d",(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25))
            conn.commit()
            cur.close()
            conn.close()
        except:
            wx.MessageBox(u"数据库连接错误！无法更新此记录。","Error")
            
    def _DelSQL(self,OnlyValue):
        conn,cur=DBConnection()
        cur.execute("delete from CON_ABN where RKEY=%d",(OnlyValue))
        conn.commit()
        cur.close()
        conn.close()
        
    def _ToolButton(self,evt):
        controller = Controller(self.toolbar.FindWindowById(2007).GetValue(),self.toolbar.FindWindowById(2008).GetValue(),self)
        controller.start()
            
    def _SetGrid(self,cur):
        DataSet=[]
        for item in cur:
            DataSet.append(MainGrid.DataSource(item))
        self._table=MainGrid.MainTable(DataSet)
        self.grid_1.SetTable(self._table)

        #隔行分色显示---------------------
        #self.grid_1.SetGridLineColour(wx.Colour(50, 50, 204))
        #self.grid_1.AutoSizeColumns()
        #for x in range(0,self.grid_1.GetNumberRows()):
            #for y in range(0,self.grid_1.GetNumberCols()):
                #if x%2==0:
                    #self.grid_1.SetCellBackgroundColour(x,y,'#9AC0CD')
        #--------------------------------
        self.grid_1.Refresh()
                
        
    def _StatusBar_ShowSelect(self,evt):
        row=self.grid_1.GetSelectedRows()
        rowLabels=[]
        for i in row:
            rowLabel=self.grid_1.GetRowLabelValue(i).encode("gbk")
            rowLabels.append(rowLabel)
        self.SetStatusText("%s" %rowLabels,1)
        evt.Skip()
 
    def OnLabelRightClicked(self,evt):
        row=evt.GetRow()
        if row==-1:
            pass
        else:
            self.rowPopup(row,evt)
        
    def rowPopup(self, row, evt):
        deleteID = wx.NewId()
        editID=wx.NewId()
        viewID=wx.NewId()
        
        #x = self.grid_1.GetRowSize(row)/2

        if not self.grid_1.GetSelectedRows():
            self.grid_1.SelectRow(row)

        menu = wx.Menu()
        xo, yo = evt.GetPosition()
        
        menu.Append(viewID,u"查看选中的记录")
        menu.Append(editID,u"修改选中的记录")
        menu.Append(deleteID, u"删除选中的记录")
        
        #def delete(event, self=self, row=row):
            #rows = self.grid_1.GetSelectedRows()
            #rowLabels=[]
            #for i in rows:
                #rowLabel=self.grid_1.GetRowLabelValue(i).encode("gbk")
                #rowLabels.append(rowLabel)
            #dlg=wx.MessageDialog(None,u"是否删除标记为%s的记录!"%rowLabels,u"警告",wx.YES_NO|wx.ICON_WARNING)
            #retval=dlg.ShowModal()
            #if retval==wx.ID_YES:
                #self._table.DeleteRows(rows)
                #self.Reset()
            #else:
                #pass
                
        self.Bind(wx.EVT_MENU,self._ViewRow,id=viewID)
        self.Bind(wx.EVT_MENU,self._DelRow,id=deleteID)
        self.Bind(wx.EVT_MENU,self._EditRow,id=editID)
        self.PopupMenu(menu, (xo+5, yo+25))
        menu.Destroy()
        return
    
    def _about(self,evt):
        dlg=AboutDialog.AboutDialog(self)
        dlg.CenterOnScreen()
        retVal = dlg.ShowModal()
        if retVal==wx.ID_CANCEL:
            dlg.Close()
            
        
            
       
class MainMenuBar(wx.MenuBar):
    def __init__(self, *args, **kwds):
        wx.MenuBar.__init__(self, *args, **kwds)
        self.fileT = wx.Menu()
        self.Append(self.fileT, u"文件")
        #self.fileT.Append(1011,u'修改密码')
        self.fileT.Append(1012,u'退出')
        
        self.editT = wx.Menu()
        self.Append(self.editT,u"编辑")
        self.editT.Append(1021,u'添加')
        self.editT.Append(1022,u'修改')
        self.editT.Append(1023,u'查看')
        self.editT.AppendSeparator()
        self.editT.Append(1024,u'删除')
        
        self.helpT = wx.Menu()
        self.Append(self.helpT, u"帮助")
        self.helpT.Append(1031,u'关于')

        self.__set_properties()
        self.__do_layout()

    def __set_properties(self):
        pass

    def __do_layout(self):
        pass



class MainToolBar(wx.ToolBar):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.TB_FLAT|wx.TB_TEXT|wx.TB_HORZ_LAYOUT|wx.TB_HORZ_TEXT
        wx.ToolBar.__init__(self, *args, **kwds)
        self.AddLabelTool(2001, u"添加  ", wx.Bitmap(addpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"添加", u"添加一条记录")
        self.AddLabelTool(2002, u"修改  ", wx.Bitmap(edtpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"修改", u"修改选中的记录")
        self.AddLabelTool(2003, u"查看  ", wx.Bitmap(detpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"详细", u"查看详细")
        self.AddLabelTool(2004, u"删除  ", wx.Bitmap(delpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"删除", u"删除选中的记录")
        self.AddLabelTool(2005, u"刷新  ", wx.Bitmap(refpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"刷新", u"刷新显示")
        self.AddLabelTool(2006, u"退出  ", wx.Bitmap(extpic, wx.BITMAP_TYPE_ANY), wx.NullBitmap, wx.ITEM_NORMAL, u"退出", u"退出应用程序")
        self.AddSeparator()
        
        self.AddControl(wx.ComboBox(self, 2007, "", choices=["", u"客户代码",u"合同号"],size=(100,-1), style=wx.CB_DROPDOWN))
        self.AddControl(wx.TextCtrl(self, 2008, "", size=(100, -1)))
        self.AddControl(wx.Button(self,2009,label="search"))
        
        self.__set_properties()
        self.__do_layout()

    def __set_properties(self):
        self.SetToolBitmapSize((22,22))
        self.Realize()

    def __do_layout(self):
        pass


#状态栏
class MainStatusbar(wx.StatusBar):
    def __init__(self, *args, **kwds):
        wx.StatusBar.__init__(self, *args, **kwds)
        self.SetFieldsCount(3)
        self.SetStatusWidths([-1,-2,-3])
        self.SetStatusText("",2)
        
        self.__set_properties()
        self.__do_layout()
        
    def __set_properties(self):
        pass
    
    def __do_layout(self):
        pass

    
#查询线程 
class Controller(threading.Thread):
    
    def __init__(self,option,value,window):
        threading.Thread.__init__(self)
        self.option=option
        self.value=value
        self.window=window
          
    def run(self):
        try:
            conn,cur=DBConnection()
            
            if self.option==u"客户代码" and self.value!="":
                cur.execute("select * from CON_ABN where CUST_CODE=%s",(self.value))
                self.window._SetGrid(cur)
                self.window.SqlHistory="select * from CON_ABN where CUST_CODE=%s" %(self.value)
              
            elif self.option==u"合同号" and self.value!="":
                cur.execute("select * from CON_ABN where CON_NO=%s",(self.value))
                self.window._SetGrid(cur)
                self.window.SqlHistory="select * from CON_ABN where CON_NO=%s" %(self.value)
            else:
                cur.execute("select * from CON_ABN ")
                self.window._SetGrid(cur)
                self.window.SqlHistory="select * from CON_ABN "

            cur.close()
            conn.close()
            
        except:
            wx.MessageBox(u"数据库连接错误！无法查询。","Error")
            
if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    main_frame = MainFrame(None, -1, "")
    main_frame.Center()
    app.SetTopWindow(main_frame)
    main_frame.Show()
    app.MainLoop()
